import React, { PureComponent } from 'react';
import { connect } from 'dva';
import {
  DownOutlined,
  PlusOutlined,
  UpOutlined,
  ExclamationCircleOutlined,
} from '@ant-design/icons';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import {
  Card,
  Button,
  Input,
  Select,
  message,
  Modal,
  Row,
  Col,
  Tabs,
  Badge,
  Spin,
  DatePicker,
  Menu,
  Dropdown,
  Divider,
} from 'antd';
import queryString from 'query-string';
import router from 'umi/router';
import StandardTable from '@/components/StandardTable';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import Authorized from '@/utils/Authorized';
import { checkPermissions } from '@/utils/authority';
import styles from '@/utils/utils.less';
import HOCSelect from '@/components/AntDesign/Select';
import TextOverFlow from '../../components/TextOverFlow';

const { Option } = Select;
const FormItem = Form.Item;
const { confirm } = Modal;
const { TabPane } = Tabs;

@connect(({ suppliermaintenance, loading, login }) => ({
  loading: loading.models.suppliermaintenance,
  activeKey: suppliermaintenance.activeKey,
  pageData: suppliermaintenance.pageData,
  formFieldsValue: suppliermaintenance.formFieldsValue,
  expandForm: suppliermaintenance.expandForm,
  valuesArr: suppliermaintenance.valuesArr,
  supplyNameList: suppliermaintenance.supplyNameList,
  baseUser: login.baseUser,
}))
@Form.create()
class BasicList extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      SUPP_STATUS: [],
      SUPPER_TAB: [],
      selectedRows: [],
      selectedRowKeys: [],
    };
    this.formItemLayout = {
      labelCol: { md: { span: 7 } },
      wrapperCol: { md: { span: 17 } },
    };
  }

  componentDidMount = () => {
    const { dispatch,
      baseUser: { userType },
    } = this.props;
    dispatch({
      type: 'suppliermaintenance/getMgrSuppListByUser',
      payload: {},
    });
    dispatch({
      type: 'publicdata/fetchDictCode',
      payload: ['SUPP_TYPE', 'SUPP_STATUS', 'SUPPER_TAB'],
    }).then(data => {
      const sortNumber = (a, b) => a.itemCode - b.itemCode;
      let suppStatus = [];
      if (data.SUPP_STATUS.length) {
        suppStatus = data.SUPP_STATUS.map(status => {
          let statusStyle = '';
          switch (status.itemCode) {
            case '1':
              statusStyle = 'default';
              break;
            case '2':
              statusStyle = 'success';
              break;
            default:
              statusStyle = 'error';
              break;
          }
          return {
            ...status,
            statusStyle,
          };
        });
      }
      this.setState({
        SUPP_STATUS: suppStatus,
        SUPPER_TAB:userType===1?data.SUPPER_TAB.sort(sortNumber):data.SUPPER_TAB.sort(sortNumber).filter(i=>i.itemName==='自主开发供应商'),
      });
    });
    this.getInitialList();
  };

  getInitialList = () => {
    const {
      pageData: { pagination },
      dispatch,
      location,
      activeKey,
      formFieldsValue,
      baseUser: { userType },

    } = this.props;
    const tempActiveKey = queryString.parse(location.search).activeKey ||(userType!==1?"2":activeKey);
    if (location.queryParam) {
      dispatch({
        type: 'suppliermaintenance/updateModelData',
        payload: { formFieldsValue: location.queryParam, expandForm: true },
      });
    }
    dispatch({
      type: 'suppliermaintenance/updateModelData',
      payload: {
        activeKey: tempActiveKey,
      },
    });
    this.searchList(
      this.processFormData({ ...formFieldsValue }),
      tempActiveKey,
      pagination.current,
      pagination.pageSize
    );
  };

  // 点击查询按钮
  searchBtnList = activeKey => {
    const { form, valuesArr, dispatch } = this.props;
    form.validateFieldsAndScroll([...valuesArr], (err, values) => {
      if (!err) {
        dispatch({
          type: 'suppliermaintenance/updateModelData',
          payload: {
            formFieldsValue: values,
            activeKey,
          },
        });
        this.searchList(this.processFormData(values), activeKey);
      }
    });
  };

  // 查询
  searchList = (
    formFieldsValue,
    activeKey = '1',
    currentPage = 1,
    pageSize = 10,
    isClear = true
  ) => {
    if (isClear) {
      this.setState({ selectedRows: [], selectedRowKeys: [] });
    }
    const { dispatch} = this.props;
    const pageArg = { currentPage, pageSize };
    const values = {
      typeFlag: activeKey,
      ...formFieldsValue,
      pageArg,
    };

    dispatch({
      type: 'suppliermaintenance/updateModelData',
      payload: {
        values,
      },
    });

    dispatch({
      type: 'suppliermaintenance/fetchList',
      payload: {
        ...values,
      },
    });
  };

  // 处理form数据
  processFormData = fieldsValue => {
    const formFieldsValue = {};
    const tempFieldsValue = fieldsValue;

    Object.keys(tempFieldsValue).forEach(key => {
      if (key === 'suppCode') {
        formFieldsValue[key] = (tempFieldsValue[key] && tempFieldsValue[key].trim()) || null;
      } else if (key === 'creTime') {
        formFieldsValue.creTime =
          (tempFieldsValue.creTime && tempFieldsValue.creTime.format('YYYY-MM-DD')) || null;
      } else if (tempFieldsValue[key] && tempFieldsValue[key].key) {
        formFieldsValue[key] =
          tempFieldsValue[key].key === undefined ? null : tempFieldsValue[key].key;
      } else {
        formFieldsValue[key] = tempFieldsValue[key] === undefined ? null : tempFieldsValue[key];
      }
    });
    if (formFieldsValue.suppCode === '') {
      formFieldsValue.suppCode = null;
    }

    return formFieldsValue;
  };

  // 点击复选框
  handleSelectRows = (selectedRows, selectedRowKeys) => {
    this.setState({ selectedRows, selectedRowKeys });
  };

  // 表格有变化：比如：切换页码
  handleStandardTableChange = pagination => {
    const { activeKey, formFieldsValue } = this.props;
    this.searchList(
      this.processFormData(formFieldsValue),
      activeKey,
      pagination.current,
      pagination.pageSize,
      false
    );
  };

  // 重置
  resetSearch = () => {
    const { form, dispatch } = this.props;
    dispatch({
      type: 'suppliermaintenance/updateModelData',
      payload: { formFieldsValue: {} },
    });
    form.resetFields();
    form.setFieldsValue({
      creTime: null,
    });
  };

  // 切换页签
  changeTabPane = activeKey => {
    const { location, formFieldsValue, dispatch } = this.props;
    router.push({
      pathname: location.pathname,
      query: {
        activeKey,
      },
    });
    dispatch({
      type: 'suppliermaintenance/updateModelData',
      payload: {
        activeKey,
        formFieldsValue: {
          ...formFieldsValue,
        },
      },
    });
    this.setState({ selectedRows: [], selectedRowKeys: [] }, () => {
      this.searchList(this.processFormData(formFieldsValue), activeKey);
    });
  };

  // 删除数据
  delList = suppId => {
    this.setState({ selectedRowKeys: [suppId] });
    const {
      pageData: { pagination },
      activeKey,
      dispatch,
      formFieldsValue,
    } = this.props;
    confirm({
      title: '你确定要删除此条供应商信息吗？',
      icon: <ExclamationCircleOutlined />,
      okText: '确定',
      okType: 'primary',
      cancelText: '取消',
      style: { top: 200 },
      onOk: () => {
        dispatch({
          type: 'suppliermaintenance/deleteMul',
          payload: { list: [suppId] },
          callback: res => {
            if (res.success) {
              message.success('删除成功！');
              this.searchList(
                this.processFormData(formFieldsValue),
                activeKey,
                pagination.current,
                pagination.pageSize
              );
            } else {
              message.warning('删除失败！');
            }
          },
        });
      },
      onCancel: () => {
        this.setState({ selectedRowKeys: [] });
      },
    });
  };

  // 修改启用停用状态
  updateStatus = (suppId, status) => {
    // status： 2启用  3:停用
    this.setState({ selectedRowKeys: [suppId] });
    const {
      pageData: { pagination },
      activeKey,
      dispatch,
      formFieldsValue,
    } = this.props;
    confirm({
      title: `你确定要${+status === 2 ? '停用' : '启用'}此供应商状态吗？`,
      icon: <ExclamationCircleOutlined />,
      okText: '确定',
      okType: 'primary',
      cancelText: '取消',
      onOk: () => {
        const newStatus = +status === 2 ? 3 : 2;
        dispatch({
          type: 'suppliermaintenance/updateStatus',
          payload: { suppId, status: newStatus },
          callback: res => {
            if (res.success) {
              message.success(`${newStatus === 2 ? '启用成功！' : '停用成功！'}`);
              this.searchList(
                this.processFormData(formFieldsValue),
                activeKey,
                pagination.current,
                pagination.pageSize
              );
              this.setState({ selectedRowKeys: [] });
            } else {
              message.warning(`${newStatus === 2 ? '启用失败！' : '停用失败！'}`);
            }
          },
        });
      },
      onCancel: () => {
        this.setState({ selectedRowKeys: [] });
      },
    });
  };

  // 修改信息
  update = (e, record) => {
    e.preventDefault();
    window.localStorage.setItem('supplyTabKey', '2');
    window.localStorage.setItem(
      'supplyInfo',
      JSON.stringify({ ...record, supplyUpdatTabKey: '1' })
    );
    router.push(`/marketingmanagement/supplyinfo/update`);
  };

  // 切换表格展开收起
  toggleForm = () => {
    const { dispatch, expandForm } = this.props;
    dispatch({
      type: 'suppliermaintenance/updateModelData',
      payload: { expandForm: !expandForm },
    });
  };

  renderSimpleForm() {
    const {
      form: { getFieldDecorator },
      formFieldsValue,
      activeKey,
      supplyNameList,
    } = this.props;
    return (
      <Form layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem {...this.formItemLayout} label="供应商编号">
              {getFieldDecorator('suppCode', {
                initialValue: formFieldsValue.suppCode,
              })(<Input placeholder="请输入" />)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem {...this.formItemLayout} label="供应商名称">
              {getFieldDecorator('suppId', {
                initialValue: formFieldsValue.suppId,
              })(
                <HOCSelect
                  placeholder="请输入"
                  labelInValue
                  showSearch
                  optionFilterProp="children"
                  allowClear
                >
                  {supplyNameList.map(options => (
                    <Option key={options.suppId} title={options.name}>
                      {options.name}
                    </Option>
                  ))}
                </HOCSelect>
              )}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <span className={styles.submitButtons}>
              <Button
                type="primary"
                htmlType="submit"
                onClick={() => this.searchBtnList(activeKey)}
              >
                查询
              </Button>
              <Button style={{ marginLeft: 8 }} onClick={this.resetSearch}>
                重置
              </Button>
              <a style={{ marginLeft: 8 }} onClick={this.toggleForm}>
                展开 <DownOutlined />
              </a>
            </span>
          </Col>
        </Row>
      </Form>
    );
  }

  renderAdvancedForm() {
    const {
      form: { getFieldDecorator },
      formFieldsValue,
      activeKey,
      supplyNameList,
    } = this.props;
    const { SUPP_STATUS } = this.state;
    // 服务状态
    const statusOL = SUPP_STATUS.map(options => (
      <Option key={options.itemCode}>{options.itemName}</Option>
    ));
    return (
      <Form layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem {...this.formItemLayout} label="供应商编号">
              {getFieldDecorator('suppCode', {
                initialValue: formFieldsValue.suppCode,
              })(<Input placeholder="请输入" />)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem {...this.formItemLayout} label="供应商名称">
              {getFieldDecorator('suppId', {
                initialValue: formFieldsValue.suppId,
              })(
                <HOCSelect
                  placeholder="请输入"
                  labelInValue
                  showSearch
                  optionFilterProp="children"
                  allowClear
                >
                  {supplyNameList.map(options => (
                    <Option key={options.suppId} title={options.name}>
                      {options.name}
                    </Option>
                  ))}
                </HOCSelect>
              )}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem {...this.formItemLayout} label="创建日期">
              {getFieldDecorator('creTime', {
                initialValue: formFieldsValue.creTime,
              })(
                <DatePicker placeholder="创建日期" style={{ width: '100%' }} format="YYYY-MM-DD" />
              )}
            </FormItem>
          </Col>
        </Row>
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem {...this.formItemLayout} label="服务状态">
              {getFieldDecorator('status', {
                rules: [{ required: false }],
                initialValue: formFieldsValue.status,
              })(
                <HOCSelect
                  placeholder="请输入关键字检索"
                  allowClear
                  showSearch
                  optionFilterProp="children"
                >
                  {statusOL}
                </HOCSelect>
              )}
            </FormItem>
          </Col>
          <Col md={8} sm={24} />
          <Col md={8} sm={24}>
            <div style={{ overflow: 'hidden' }}>
              <span style={{ float: 'right', marginBottom: 24 }}>
                <Button
                  type="primary"
                  htmlType="submit"
                  onClick={() => this.searchBtnList(activeKey)}
                >
                  查询
                </Button>
                <Button style={{ marginLeft: 8 }} onClick={this.resetSearch}>
                  重置
                </Button>
                <a style={{ marginLeft: 8 }} onClick={this.toggleForm}>
                  收起 <UpOutlined />
                </a>
              </span>
            </div>
          </Col>
        </Row>
      </Form>
    );
  }

  renderForm() {
    const { expandForm } = this.props;
    return expandForm ? this.renderAdvancedForm() : this.renderSimpleForm();
  }

  render() {
    const {
      pageData,
      loading,
      activeKey,
      baseUser: { userType },
    } = this.props;
    const { selectedRows, selectedRowKeys, SUPPER_TAB, SUPP_STATUS } = this.state;
    console.log('userType', userType);
    const columns = [
      {
        title: '供应商编号',
        dataIndex: 'suppCode',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
      },
      {
        title: '供应商名称',
        dataIndex: 'name',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        render: text => <TextOverFlow text={text} />,
      },
      {
        title: '供应商类型',
        dataIndex: 'typeName',
        align: 'center',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
      },
      {
        title: '服务状态',
        dataIndex: 'status',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        render: val =>
          SUPP_STATUS.map(status => {
            if (status.itemCode === `${val}`) {
              return (
                <Badge key={status.itemCode} status={status.statusStyle} text={status.itemName} />
              );
            }
            return null;
          }),
      },
      {
        title: '操作',
        dataIndex: 'operation',
        onHeaderCell: () => ({ style: { fontWeight: 'bold', width: 150, textAlign: 'center' } }),
        onCell: () => ({ style: { textAlign: 'center' } }),
        render: (text, record) => (
          <span>
            <a
              onClick={() =>
                router.push(
                  `/supplymanage/protection/detail?suppId=${record.suppId}&activeKey=${activeKey}`
                )
              }
            >
              查看
            </a>
            {userType === 1 ? <Divider type="vertical" /> : null}
            {userType === 1 ? (
              <Dropdown
                overlay={
                  <Menu>
                    {checkPermissions('business:supplier:updatePla') && (
                      <Menu.Item
                        onClick={() =>
                          router.push(
                            `/supplymanage/protection/update?suppId=${
                              record.suppId
                            }&activeKey=${activeKey}`
                          )
                        }
                      >
                        修改
                      </Menu.Item>
                    )}
                    {record.status === 1
                      ? checkPermissions('business:supplier:deleteMul') && (
                          // eslint-disable-next-line react/jsx-indent
                          <Menu.Item key="delete" onClick={() => this.delList(record.suppId)}>
                            删除
                          </Menu.Item>
                        )
                      : null}
                    {checkPermissions('business:supplier:updateStatus') && (
                      <Menu.Item
                        key="able"
                        style={{ textAlign: 'center', cursor: 'pointer' }}
                        onClick={() => this.updateStatus(record.suppId, record.status)}
                      >
                        {record.status === 2 ? '停用' : '启用'}
                      </Menu.Item>
                    )}
                  </Menu>
                }
              >
                <a>
                  更多 <DownOutlined />
                </a>
              </Dropdown>
            ) : null}
          </span>
        ),
      },
    ];
    const columnsSelf = [
      {
        title: '供应商编号',
        dataIndex: 'suppCode',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
      },
      {
        title: '供应商名称',
        dataIndex: 'name',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        render: text => <TextOverFlow text={text} />,
      },

      {
        title: '服务状态',
        dataIndex: 'status',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        render: val =>
          SUPP_STATUS.map(status => {
            if (status.itemCode === `${val}`) {
              return (
                <Badge key={status.itemCode} status={status.statusStyle} text={status.itemName} />
              );
            }
            return null;
          }),
      },
      {
        title: '操作',
        dataIndex: 'operation',
        onHeaderCell: () => ({ style: { fontWeight: 'bold', width: 150, textAlign: 'center' } }),
        onCell: () => ({ style: { textAlign: 'center' } }),
        render: (text, record) => (
          <span>
            <Authorized authority="business:supplier:update" noMatch={null}>
              <a
                onClick={() =>
                  router.push(
                    `/supplymanage/protection/update?suppId=${record.suppId}&activeKey=${activeKey}`
                  )
                }
              >
                修改
              </a>
            </Authorized>
            <Authorized authority="business:supplier:update" noMatch={null}>
              <Divider type="vertical" />
            </Authorized>
            <Dropdown
              overlay={
                <Menu>
                  <Menu.Item
                    key="view"
                    onClick={() =>
                      router.push(
                        `/supplymanage/protection/detail?suppId=${
                          record.suppId
                        }&activeKey=${activeKey}`
                      )
                    }
                  >
                    查看
                  </Menu.Item>
                  {record.status === 1
                    ? checkPermissions('business:supplier:deleteMul') && (
                        // eslint-disable-next-line react/jsx-indent
                        <Menu.Item key="delete" onClick={() => this.delList(record.suppId)}>
                          删除
                        </Menu.Item>
                      )
                    : null}
                  {checkPermissions('business:supplier:updateStatus') && (
                    <Menu.Item
                      key="able"
                      style={{ textAlign: 'center', cursor: 'pointer' }}
                      onClick={() => this.updateStatus(record.suppId, record.status)}
                    >
                      {record.status === 2 ? '停用' : '启用'}
                    </Menu.Item>
                  )}
                </Menu>
              }
            >
              <a>
                更多 <DownOutlined />
              </a>
            </Dropdown>
          </span>
        ),
      },
    ];
    const platformSupply = (
      <div>
        <Row style={{ marginBottom: 16 }}>
          <Authorized authority="business:supplier:insertPla" noMatch={null}>
            <Button
              type="primary"
              onClick={() => router.push(`/supplymanage/protection/add?activeKey=${activeKey}`)}
              style={{ marginRight: 8 }}
            >
              <PlusOutlined />
              新增
            </Button>
          </Authorized>
          {checkPermissions('business:supplier:insertPla') && (
            <Authorized authority="business:supplier:uploadSupp" noMatch={null}>
              <Button onClick={() => router.push(`/supplymanage/protection/batch`)}>
                批量新增
              </Button>
            </Authorized>
          )}
        </Row>
        <StandardTable
          selectedRows={selectedRows}
          selectedRowKeys={selectedRowKeys}
          loading={loading}
          data={pageData}
          rowKey="suppId"
          columns={columns}
          onSelectRow={this.handleSelectRows}
          onChange={this.handleStandardTableChange}
        />
      </div>
    );
    const selfSupply = (
      <div>
        <Row style={{ marginBottom: 16 }}>
          <Authorized authority="business:supplier:insert" noMatch={null}>
            <Button
              type="primary"
              onClick={() => router.push(`/supplymanage/protection/add?activeKey=${activeKey}`)}
              style={{ marginRight: 8 }}
            >
              <PlusOutlined />
              新增
            </Button>
          </Authorized>
          {checkPermissions('business:supplier:insert') && (
            <Authorized authority="business:supplier:uploadSupp" noMatch={null}>
              <Button onClick={() => router.push(`/supplymanage/protection/batch`)}>
                批量新增
              </Button>
            </Authorized>
          )}
        </Row>
        <StandardTable
          selectedRows={selectedRows}
          selectedRowKeys={selectedRowKeys}
          loading={loading}
          data={pageData}
          rowKey="suppId"
          columns={columnsSelf}
          onSelectRow={this.handleSelectRows}
          onChange={this.handleStandardTableChange}
        />
      </div>
    );
    // 获取页签组件
    const getTabPane = active => {
      switch (active) {
        case '1':
          return platformSupply;
        case '2':
          return selfSupply;
        default:
          return <div />;
      }
    };
    return (
      <PageHeaderWrapper>
        <Spin tip="Loading..." spinning={loading}>
          <Card className={styles.searchCard}>
            <div className={styles.tableListForm}>{this.renderForm()}</div>
          </Card>
          <Card className={styles.tabCard}>
            <Tabs activeKey={activeKey} onChange={this.changeTabPane}>
              {SUPPER_TAB.map(pane => (
                <TabPane tab={<Badge dot={pane.isHas}>{pane.itemName}</Badge>} key={pane.itemCode}>
                  {getTabPane(pane.itemCode)} 
                </TabPane>
              ))}
            </Tabs>
          </Card> 
        </Spin>
      </PageHeaderWrapper>
    );
  }
}
const ListSearchForm = Form.create()(BasicList);
export default ListSearchForm;
